<!--
 * @Description: 表格填报
 * @Author: qingyang
 * @Date: 2022-06-01 14:10:03
 * @LastEditors: qingyang
 * @LastEditTime: 2023-03-21 15:36:25
-->
<template>
  <CTable
    border
    useDataSource
    :dataSource="tableData"
    :pagination="false"
    :extraTableOption="{
      spanMethod: cellMerge
    }"
  >
    <vxe-column title="温室气体源类型" field="ghgSourceName" show-overflow show-header-overflow>
      <template #default="scope">
        {{ empty(scope.row.ghgSourceName) }}
      </template>
    </vxe-column>
    <vxe-column title="排放源" field="sourceName" show-overflow show-header-overflow>
      <template #default="scope">
        {{ empty(scope.row.sourceName) }}
      </template>
    </vxe-column>
    <vxe-column
      title="能源/燃料"
      field="materialName"
      show-overflow
      show-header-overflow
      width="250"
    >
      <template #default="scope">
        {{ empty(scope.row.materialName) }}
      </template>
    </vxe-column>
    <vxe-column
      title="负责部门"
      field="department"
      show-overflow
      show-header-overflow
      class="select-wrap"
    >
      <template #default="scope">
        <template v-if="!props.readonly">
          <CSelect
            v-if="departmentOptions.length"
            v-model="scope.row.department"
            class="table-select"
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :value="item.dataValue"
              :label="item.dataValue"
            >
            </el-option>
          </CSelect>
          <CTableEditCell
            v-else
            v-model="scope.row.department"
            :tableRow="scope.row"
            trigger="click-cell"
            :alwaysShowIcon="false"
            placeholder="请输入"
            showPlaceholderStyle
          ></CTableEditCell>
        </template>

        <span v-else>{{ scope.row.department }}</span>
      </template>
    </vxe-column>
    <vxe-column title="活动数据" field="activityData" show-overflow show-header-overflow>
      <template #default="scope">
        <CTableEditCell
          v-model="scope.row.activityData"
          :tableRow="scope.row"
          align="right"
          trigger="click-cell"
          inputType="number"
          :local-value-formatter="handleLocalValueFormatter"
          :isError="scope.row.isError"
          :updateFn="handleActivityDataUpdate"
          placeholder="请输入"
          showPlaceholderStyle
          alwaysInput
          :alwaysShowIcon="false"
          hover="row-hover"
          v-if="!props.readonly"
          @change="scope.row.dataSource = 'MANUAL'"
        ></CTableEditCell>
        <span class="algin-right" v-else>{{ thousandFormat(scope.row.activityData) }}</span>
      </template>
    </vxe-column>
    <vxe-column
      title="数据单位"
      field="activityDataUnit"
      show-overflow
      show-header-overflow
      width="100"
    >
      <template #default="scope">
        {{ empty(scope.row.activityDataUnit) }}
      </template>
    </vxe-column>
    <vxe-column title="填报方式" field="dataSource" show-overflow show-header-overflow width="100">
      <template #default="scope">
        <el-tag class="g-tag" hit
          >{{ scope.row.dataSource == 'EMS' ? 'EMS获取' : '手工填写' }}
        </el-tag>
      </template>
    </vxe-column>
    <vxe-column title="操作" width="100" v-if="!props.readonly">
      <template #default="scope">
        <el-button
          text
          type="primary"
          @click="handlerThrottle(scope.row, scope.$index)"
          v-if="scope.row.emsDeviceIds && scope.row.emsDeviceIds.length > 0"
          >EMS获取</el-button
        >
      </template>
    </vxe-column>
  </CTable>
</template>
<script lang="ts">
export default {
  name: 'FillTable'
};
</script>
<script lang="ts" setup>
import { defineProps, defineEmits, computed, ref } from 'vue';
import { empty, limitStrLength, thousandFormat } from '@/utils';
import { CTableEditCell } from '@/components/CTableEditCell';
import { CTable } from '@/components/CTable';
import { getSystemDict } from '@/apis/common/common';
import { CSelect } from '@/components/CSelect';
import { relateEms } from '@/apis/eci/inventory/inventory';
import { useMessage } from '@/hooks/useMessage';
import { useDebounceFn } from '@vueuse/core';

const props = defineProps({
  taskNo: {
    type: String,
    default: ''
  },
  readonly: {
    type: Boolean,
    default: false
  },
  data: {
    type: Array,
    default: () => {
      return [];
    }
  }
});
const emit = defineEmits(['update:data', 'refresh']);
const { createMessage } = useMessage();
const tableData = computed({
  get: () => {
    getSpanArr(props.data);
    return props.data;
  },
  set: val => {
    emit('update:data', val);
  }
});
let spanEmissionCategory: number[] = [];
const departmentOptions = ref<any[]>([]);
const loadDepartmentOptions = async () => {
  let data = await getSystemDict('inventory:department');
  departmentOptions.value = data ?? [];
};
loadDepartmentOptions();
const posSpanEmissionCategory = ref(0); // 类型
const getSpanArr = (data: any) => {
  spanEmissionCategory = [];
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanEmissionCategory.push(1);
      posSpanEmissionCategory.value = 0;
    } else {
      // 判断当前元素与上一个元素是否相同
      if (
        data[i].ghgSourceName === data[i - 1].ghgSourceName &&
        data[i].emissionScope === data[i - 1].emissionScope
      ) {
        spanEmissionCategory[posSpanEmissionCategory.value] += 1;
        spanEmissionCategory.push(0);
      } else {
        spanEmissionCategory.push(1);
        posSpanEmissionCategory.value = i;
      }
    }
  }
};
const cellMerge = ({ rowIndex, columnIndex }: any) => {
  if (columnIndex === 0) {
    const _row = spanEmissionCategory[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col
    };
  }
};

// localValue的格式化
function handleLocalValueFormatter(value: number) {
  console.log('handleLocalValueFormatter', value, Number(value));
  const res = limitStrLength(value, 6);
  console.log('handleLocalValueFormatter res', res);
  return res;
}
function handleActivityDataUpdate(value: any, row: any): Promise<boolean> {
  console.log('handleActivityDataUpdate', value, row);
  if (value || value === 0) {
    row.isError = false;
  } else {
    row.isError = true;
  }
  return Promise.resolve(true);
}

const handleEms = (row: any, index: number) => {
  relateEms(row.dataNo).then(() => {
    createMessage.success('ems获取成功');
    emit('refresh', row.dataNo);
  });
};
const handlerThrottle = useDebounceFn(handleEms, 300);
</script>
<style lang="scss" scoped>
.select-wrap {
  background: red;
}

.algin-right {
  display: inline-block;
  width: 100%;
  text-align: right;
}

.table-select {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  :deep(.el-input__wrapper) {
    height: 43px;
    border-radius: 0;
  }
}
</style>
